<?php

// 应用公共文件

/**
 * 获取用户ip
 * @return array|false|string
 */
function getRemoteIPAddress()
{
    global $ip;
    if (getenv("HTTP_CLIENT_IP"))
        $ip = getenv("HTTP_CLIENT_IP");
    else if (getenv("HTTP_X_FORWARDED_FOR"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if (getenv("REMOTE_ADDR"))
        $ip = getenv("REMOTE_ADDR");
    else $ip = "Unknow";
    return $ip;
}

function mobile_curl($url, $status = false)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 1000);
    //curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36');
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4');
    if ($status) {
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept:application', 'X-Request:JSON', 'X-Requested-With:XMLHttpRequest'));
    }

    //如果用的协议是https则打开鞋面这个注释
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

    $res = curl_exec($curl);
    curl_close($curl);
    return $res;
}

/**
 * banner api地址
 * @return string
 */
function banner_url()
{
    $url = "http://c.m.163.com/nc/article/headline/list/0-10.html?from=toutiao&passport=&devId";
    return $url;
}

/**
 * 新闻列表url
 * @param $news_type
 * @param $page
 * @return string
 */
function new_list_url($news_type, $page)
{
    $url = "http://c.m.163.com/nc/article/headline/{$news_type}/{$page}-10.html";
    return $url;
}

/**
 * 新闻详情
 * @param $id
 * @return string
 */
function new_detail_url($id)
{
    $url = "http://c.m.163.com/nc/article/{$id}/full.html";
    return $url;
}

/**
 * 当地新闻列表
 * @param $name
 * @param $page
 * @return string
 */
function local_news_url($name, $page)
{
    $url = "http://3g.163.com/touch/jsonp/article/local/{$name}/{$page}-10.html";
    return $url;
}


//获取东方财富的数据,组装数据返回数组
function get_east($pageNumber = 1)
{

    $url = 'http://datacenter-web.eastmoney.com/api/data/v1/get?callback=jQuery11230831006588016656_1628042556050&sortColumns=PUBLIC_START_DATE&sortTypes=-1&pageSize=50&pageNumber=' . $pageNumber . '&reportName=RPT_BOND_CB_LIST&columns=ALL&quoteColumns=f2~01~CONVERT_STOCK_CODE~CONVERT_STOCK_PRICE%2Cf235~10~SECURITY_CODE~TRANSFER_PRICE%2Cf236~10~SECURITY_CODE~TRANSFER_VALUE%2Cf2~10~SECURITY_CODE~CURRENT_BOND_PRICE%2Cf237~10~SECURITY_CODE~TRANSFER_PREMIUM_RATIO%2Cf239~10~SECURITY_CODE~RESALE_TRIG_PRICE%2Cf240~10~SECURITY_CODE~REDEEM_TRIG_PRICE%2Cf23~01~CONVERT_STOCK_CODE~PBV_RATIO&source=WEB&client=WEB';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    $html = curl_exec($ch);
    //删除最后两位字符串
    $html = rtrim($html, ");");
    $sbusrt_start = strpos($html, '"version"') - 1;
    $html = substr($html, $sbusrt_start);
    curl_close($ch);
    $datas = json_decode($html, true);
    $jisilu_data = [];
    if (count($datas) > 0) {
        $jisilu_data_format = $datas['result']['data'];
        if ($jisilu_data_format) {
            foreach ($jisilu_data_format as $key => $value) {
                if ($value['CURRENT_BOND_PRICE'] != '-') {
                    //                dump($value['CURRENT_BOND_PRICE']);
                    //                dump($value['TRANSFER_PREMIUM_RATIO']);die;
                    $jisilu_data[$key]['redeem_flag'] = $value['REDEEM_TYPE'] ? 'Y' : 'N';
                    $jisilu_data[$key]['bond_id'] = $value['SECURITY_CODE'];
                    $jisilu_data[$key]['bond_nm'] = $value['SECURITY_NAME_ABBR'];
                    $jisilu_data[$key]['price'] = $value['CURRENT_BOND_PRICE'];
                    $jisilu_data[$key]['premium_rt'] = $value['TRANSFER_PREMIUM_RATIO'];
                    $jisilu_data[$key]['dblow'] = $value['CURRENT_BOND_PRICE'] + $value['TRANSFER_PREMIUM_RATIO'];
                    $jisilu_data[$key]['btype'] = '';
                    $jisilu_data[$key]['curr_iss_amt'] = $value['ACTUAL_ISSUE_SCALE'];
                    $jisilu_data[$key]['rating_cd'] = $value['RATING'];
                }
            }
        }
    }

    return $jisilu_data;
}

//获取集思录数据，如果python没搞定就拿上面的东方财富数据
function jisilu_east(){ 
    header('Content-type:text/html;charset=utf-8');
        if (empty(file_get_contents('/www/wwwroot/convertible_bond/lib/testdata/' . 'jisilu.json'))) {
            $page = 1;
            $east = [];
            do {
                $seconds = rand(1, 5);
                sleep($seconds);
                $east[$page] = get_east($page);
                if (count($east[$page]) > 0) {
                    $go = true;
                } else {
                    $go = false;
                }
                $page++;
            } while ($go);


            $enddata = [];
            foreach ($east as $value) {
                foreach ($value as $vv) {
                    if ($vv['price']) {
                        $enddata[] = $vv;
                    }
                }
            }
        } else {
            $jisiluData = json_decode(file_get_contents('/www/wwwroot/convertible_bond/lib/testdata/' . 'jisilu.json'), true);
            if (count($jisiluData['rows']) < 100) {
                $page = 1;
                $east = [];
                do {
                    $seconds = rand(1, 5);
                    sleep($seconds);
                    $east[$page] = get_east($page);
                    if (count($east[$page]) > 0) {
                        $go = true;
                    } else {
                        $go = false;
                    }
                    $page++;
                } while ($go);


                $enddata = [];
                foreach ($east as $value) {
                    foreach ($value as $vv) {
                        if ($vv['price']) {
                            $enddata[] = $vv;
                        }
                    }
                }
            } else {
                $enddata = [];
                foreach ($jisiluData['rows'] as $key => $value) {
                    $enddata[$key]['redeem_flag'] = $value['cell']['redeem_flag'];
                    $enddata[$key]['bond_id'] = $value['cell']['bond_id'];
                    $enddata[$key]['bond_nm'] = $value['cell']['bond_nm'];
                    $enddata[$key]['price'] = $value['cell']['price'];
                    $enddata[$key]['premium_rt'] = $value['cell']['premium_rt'];
                    $enddata[$key]['dblow'] = $value['cell']['dblow'];
                    $enddata[$key]['btype'] = $value['cell']['btype'];
                    $enddata[$key]['curr_iss_amt'] = $value['cell']['curr_iss_amt'];
                    $enddata[$key]['rating_cd'] = $value['cell']['rating_cd'];
                }
                file_put_contents('/www/wwwroot/convertible_bond/lib/testdata/' . 'jisilu.json', '');
            }
        }
return $enddata;
}

 /**
     * tp5邮件
     * @param
     * @return mixed
     * @author staitc7 <static7@qq.com>
     */
    function email($mailer = "雪球网", $title, $body)
    {

        $toemail = '80837879@qq.com'; //定义收件人的邮箱

        $mail = new \PHPMailer\PHPMailer\PHPMailer();

        $mail->isSMTP(); // 使用SMTP服务
        $mail->CharSet = "utf8"; // 编码格式为utf8，不设置编码的话，中文会出现乱码
        $mail->Host = "smtp.sina.com"; // 发送方的SMTP服务器地址
        $mail->SMTPAuth = true; // 是否使用身份验证
        $mail->Username = "peofy@sina.com"; // 发送方的163邮箱用户名，就是你申请163的SMTP服务使用的163邮箱</span><span style="color:#333333;">
        $mail->Password = "406121a5649b696d"; // 发送方的邮箱密码，注意用163邮箱这里填写的是“客户端授权密码”而不是邮箱的登录密码！</span><span style="color:#333333;">
        $mail->SMTPSecure = "ssl"; // 使用ssl协议方式</span><span style="color:#333333;">
        $mail->Port = 465; // 163邮箱的ssl协议方式端口号是465/994

        $mail->setFrom("peofy@sina.com", "$mailer"); // 设置发件人信息，如邮件格式说明中的发件人，这里会显示为Mailer(xxxx@163.com），Mailer是当做名字显示
        $mail->addAddress($toemail, 'Yang'); // 设置收件人信息，如邮件格式说明中的收件人，这里会显示为Liang(yyyy@163.com)
        $mail->addReplyTo("peofy@sina.com", "Reply"); // 设置回复人信息，指的是收件人收到邮件后，如果要回复，回复邮件将发送到的邮箱地址
        //$mail->addCC("xxx@163.com");// 设置邮件抄送人，可以只写地址，上述的设置也可以只写地址(这个人也能收到邮件)
        //$mail->addBCC("xxx@163.com");// 设置秘密抄送人(这个人也能收到邮件)
        //$mail->addAttachment("bug0.jpg");// 添加附件


        $mail->Subject = date('Y-m-d H:i:s') . $title; // 邮件标题
        $mail->Body = $body; // 邮件正文
        //$mail->AltBody = "This is the plain text纯文本";// 这个是设置纯文本方式显示的正文内容，如果不支持Html方式，就会用到这个，基本无用

        if (!$mail->send()) { // 发送邮件
            echo "Message could not be sent.";
            echo "Mailer Error: " . $mail->ErrorInfo;
            die; // 输出错误信息
        } else {
            return 200;
        }
    }
